<%@tag import="by.epam.communalservices.dao.jdbc.JdbcDaoUser"%>
<%@tag import="by.epam.communalservices.entity.User"%>
<%@tag import="java.sql.Connection"%>
<%@tag import="java.lang.*"%>
<%@ attribute name="id" required="true"%>
<%@ attribute name="login"%>
<%@ attribute name="passw"%>
<%@ attribute name="delete"%>
<%@ attribute name="submit"%>

<%
    request.setAttribute("message", "");

    Connection con = (Connection) request.getSession().getAttribute("currentConnection");
    User user = null;
    JdbcDaoUser userDao = new JdbcDaoUser(con);
    if (getJspContext().getAttribute("id") != "" && Long.parseLong(getJspContext().getAttribute("id").toString()) > 0) {
        user = userDao.read(Long.parseLong(getJspContext().getAttribute("id").toString()));
        if (getJspContext().getAttribute("submit") != "") {
            user.setLogin(getJspContext().getAttribute("login").toString());
            user.setPassw(getJspContext().getAttribute("passw").toString());
            userDao.update(user.getId(), user);
            request.setAttribute("message", "User Updated");
        }
    } else if (getJspContext().getAttribute("delete") != "") {
        userDao.delete(Long.parseLong(getJspContext().getAttribute("delete").toString()));
        request.setAttribute("message", "User deleted");
    } else {
        user = new User();
        if (getJspContext().getAttribute("submit") != "") {
            user.setLogin(getJspContext().getAttribute("login").toString());
            user.setPassw(getJspContext().getAttribute("passw").toString());
            user.setId(userDao.create(user));
            request.setAttribute("message", "User Created");
        }
    }
    if (user == null) {
        request.setAttribute("form", false);
        if (getJspContext().getAttribute("delete") == null) {
            request.setAttribute("message", "User Not Found");
        }
    } else {
        request.setAttribute("form", true);
        request.setAttribute("user", user);
    }
%>